<template>
  <el-dialog :title="title" :visible="visible" @close="handleClose" width="800px">
    <el-form :model="formAdd" label-position="right" label-width="90px" ref="formRef" :rules="rules">
      <el-form-item label="规则名称" prop="ruleName">
        <el-input v-model="formAdd.ruleName" placeholder="请输入规则名称"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formAdd.sort" @input="handleInput" placeholder="请输入排序"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveForm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {
    saveRuleInfo, //新增规则
    putRule //修改规则
  } from '@/api/basic/PersonnelInformation.js'
  export default {
    data() {
      return {
        title: '新增规则',
        formAdd: {
          ruleName: '',
          sort: ''
        },
        rules: {
          ruleName: [{
            required: true,
            message: '请输入规则名称',
            trigger: 'blur'
          }],
          sort: [{
            required: true,
            message: '请输入排序',
            trigger: 'blur'
          }]
        }
      }
    },
    props: {
      visible: { // 接收父组件通过sync传递的visible属性
        type: Boolean,
        default: false
      }
    },
    created() {

    },
    methods: {
      handleInput(value) {
        this.formAdd.sort = value.replace(/[^\d]/g, '');
      },
      openDialog(type, row) {
        this.title = type === 'edit' ? '编辑规则' : '新增规则';
        // 根据类型区分新增和编辑逻辑
        if (type === 'edit' && row) {
          console.log(row, 666);
          this.formAdd = {
            ...row
          };
          this.formAdd.id = row.id;
        } else {
          this.formAdd = {
            ruleName: '',
            sort: '',
            parentId: row.id
          }
        }
      },
      // 提取重置表单的逻辑
      handleClose() {
        // 通过事件通知父组件更新visible值，触发update:visible事件
        this.$nextTick(() => {
          this.$refs.formRef.resetFields();
        })
        this.$emit('update:visible', false);
      },
      //提交规则关联
      saveForm() {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            const apiMethod = this.title === '新增规则' ? saveRuleInfo : putRule;
            apiMethod(this.formAdd).then(res => {
              this.$emit('addSuccess'); // 通知父组件添加成功
              this.$message({
                message: res.msg, // 显示成功消息
                type: 'success',
              });
              this.handleClose();
            })
          }
        })
      },
    }
  }
</script>

<style>
</style>
